import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeleteResult, Repository, UpdateResult } from 'typeorm';
import { Bk_Outstanding_Students } from './bk_outstanding_students.entity';
import * as fs from 'fs';
import { join } from 'path';
import { v1 } from 'node-uuid';

@Injectable()
export class OutstandingStudentsService {
    constructor(
        @InjectRepository(Bk_Outstanding_Students)
        private readonly outstandingStudentsRepository: Repository<Bk_Outstanding_Students>
    ) { }

    async add(files: any, student: any): Promise<Bk_Outstanding_Students> {
        const photo = v1() + '.' + files.photo[0].originalname.split('.')[1];
        fs.writeFileSync(join(__dirname, '..', 'public', 'image', photo), files.photo[0].buffer);
        student.photo = photo;
        return await this.outstandingStudentsRepository.save(student);
    }

    async delete(id: number): Promise<DeleteResult> {
        const { student_name, photo } = await this.outstandingStudentsRepository.findOne({ where: { id } });
        fs.unlink(join(__dirname, '..', 'public', 'image', photo), () => console.log(`删除 ${student_name} 照片成功！`));
        return await this.outstandingStudentsRepository.delete(id);
    }

    async update(id: number, files: any, student: any): Promise<UpdateResult> {
        const { photo } = await this.outstandingStudentsRepository.findOne({ where: { id } });
        fs.writeFileSync(join(__dirname, '..', 'public', 'image', photo), files.photo[0].buffer);
        return await this.outstandingStudentsRepository.update(id, student);
    }

    async findAll(query: any): Promise<[Bk_Outstanding_Students[], number]> {
        return await this.outstandingStudentsRepository.findAndCount({
            where: { year: query.year },
            skip: query.skip,
            take: query.take,
            order: { score: "DESC" }
        })
    }

    async getStudentsByYear(query: any): Promise<[Bk_Outstanding_Students[], number]> {
        return await this.outstandingStudentsRepository.findAndCount({
            where: { year: query.year },
            skip: query.skip,
            take: query.take,
            order: { score: "DESC" }
        })

    }
}
